package com.ccx.library.module.role.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccx.library.module.role.entity.Role;
import com.ccx.library.module.role.service.RoleService;
import com.ccx.library.module.parallel.service.UserRoleService;
import com.ccx.library.response.R;
import com.ccx.library.util.ModelVoIdUtil;
import com.ccx.library.util.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @GetMapping("/query")
    public R Query(Role role){
        return R.SUCCESS(roleService.getOne(WrapperUtil.Query(role)));
    }
    @GetMapping
    public R list(){
        return R.SUCCESS(roleService.list(WrapperUtil.orderDesc(Role.class)));
    }
    @PostMapping
    public R save(@RequestBody Role role){
        return transactionTemplate.execute(status -> {
            role.setRoleLevel(roleService.count());
            try {
                roleService.save(role);
            }catch (Exception e){
                status.setRollbackOnly();
            }
            return R.SUCCESS();
        });
    }
    @PutMapping
    public R edit(@RequestBody Role role){
        return R.SUCCESS(roleService.update(WrapperUtil.Update(role, ModelVoIdUtil.getId(role),role.getRoleId())));
    }
    @DeleteMapping
    public R deleteBatch(@RequestBody List<String> ids){
        return R.SUCCESS(roleService.removeByIds(ids));
    }
}
